package com.yunshang.shoppingmall.shopping.WeChat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yunshang.shoppingmall.common.HttpRequest;
import com.yunshang.shoppingmall.common.MessageConstants;
import com.yunshang.shoppingmall.common.Response;
import com.yunshang.shoppingmall.entity.User;
import com.yunshang.shoppingmall.entity.UserNo;
import com.yunshang.shoppingmall.service.SysUserNoService;
import com.yunshang.shoppingmall.service.UserService;
import com.yunshang.shoppingmall.shopping.WeChat.common.WinChat;
import com.yunshang.shoppingmall.shopping.WeChat.common.WinxinUtil;
import com.yunshang.shoppingmall.shopping.WeChat.service.WeixinCoreService;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;


@RestController
@RequestMapping(value="/wechat")
public class WeChatMsgController {

    private static Logger logger = LoggerFactory.getLogger(WeChatMsgController.class);

    @Autowired
    private WeixinCoreService weixinCoreService;

    @Autowired
    SysUserNoService sysUserNoService;

    @Autowired
    UserService userService;

    @RequestMapping(value = "/access")
    public String WeChatInterface(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        // 在响应消息（回复消息给用户）时，也将编码方式设置为UTF-8，原理同上；
        response.setCharacterEncoding("UTF-8");

        System.out.println("AA开始接收数据!!");

        String respXml = weixinCoreService.weixinMessageHandelCoreService(request, response);
        if (respXml==null){
            logger.error("-------------处理微信消息失败-----------------------");
            return null;
        }else {
            logger.info("----------返回微信消息处理结果-----------------------:"+respXml);
            return respXml;
        }
    }

    @RequestMapping(value = "/code")
    public String code(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String code = request.getParameter("code");
        System.out.println(code + "aaa");
        if (code != null && !code.equals("") && !code.toLowerCase().equals("null")) {
            try {
                Response response1 = getOpendId(code, request);
                if (response1.getMsgCode()=="000000") {

                    String openid = response1.getData().toString();

                    request.getSession().setAttribute("wopenid",openid);
                    request.getSession().setAttribute("wcode",code);

                    response.sendRedirect("/wechat/blWechatPhone?openid="+openid);

                } else {

                }
            } catch (Exception ex) {
                return ex.getMessage();
            }

        } else {
            System.out.println(code + "a222");
            String redirect_uri = WinChat.severUrl + "/wechat/code";
            String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                    "appid=" + WinChat.appid + "" +
                    "&redirect_uri=" + redirect_uri + "" +
                    "&response_type=code" +
                    "&scope=snsapi_userinfo" +
                    "&state=STATE#wechat_redirect";
            try {
                response.sendRedirect(url);
            } catch (Exception e) {
            }
        }
//        HttpSession httpSession = request.getSession();
//        httpSession.setAttribute("openid","xxxxx");
//        String weUrl =(String)httpSession.getAttribute("weurl");
//        response.sendRedirect(weUrl);
        return "";
    }

    @RequestMapping(value = "/blWechatPhone")
    public String blWechatPhone(HttpServletRequest request, HttpServletResponse response) throws Exception {

        System.out.println("XXXX");

        String openid = request.getParameter("openid");

        System.out.println("openid:"+openid);
        HttpSession httpSession = request.getSession();
        httpSession.removeAttribute("xPhone");
        User user = userService.selectUserByOpenid(openid);
        if(user==null)
        {
            httpSession.setAttribute("wPhone","1");

            //转向绑定手机
            response.sendRedirect("/wap/wechatPhone");
            return "wechatPhone_A";
        }
        else {
            httpSession.setAttribute("dlopenid",openid);
            String url = (String) httpSession.getAttribute("weurl");
            if (url != null) {
                response.sendRedirect(url);
            }
            else
            {
                return "wechatPhone_weurl";
            }
        }
        return "程序错误";
    }

    public Response getOpendId(String code, HttpServletRequest request) throws IOException {

        HttpSession session = request.getSession();
        if (code != null && !code.equals("")) {
            //获取openid和access_token的连接
            String getOpenIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                    "appid=" + WinChat.appid + "" +
                    "&secret=" + WinChat.appsecret + "" +
                    "&code=" + code + "" +
                    "&grant_type=authorization_code";
            try {
                //获取返回的code
                String requestUrl = getOpenIdUrl.replace("CODE", code);
                CloseableHttpClient httpClient = HttpClients.createDefault();
                HttpGet httpGet = new HttpGet(requestUrl);
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                //向微信发送请求并获取response
                String response = httpClient.execute(httpGet, responseHandler);
                System.out.println("=========================获取token===================");
                System.out.println(response);
                //JsonParser parser = new JsonParser();
                JSONObject jsonObject = JSON.parseObject(response);
                //JsonObject jsonObject = (JsonObject) parser.parse(response);
                String access_token = jsonObject.get("access_token").toString();
                String openId = jsonObject.get("openid").toString();
                //session.setAttribute("openid", openId);

                System.out.println("=======================用户access_token==============");
                System.out.println(access_token);
                System.out.println(openId);

//                HttpSession wxSession = request.getSession();
//                wxSession.setAttribute("openId", openId);
//                wxSession.setAttribute("accessToken", access_token);

//                //获取用户基本信息的连接
                String access_token1 = WinxinUtil.getToken(WinChat.appid, WinChat.appsecret);
                String getUserInfo = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
                String userInfoUrl = getUserInfo.replace("ACCESS_TOKEN", access_token1).replace("OPENID", openId);
                System.out.println("userInfoUrl:"+userInfoUrl);
                String userInfo = HttpRequest.getHttp(userInfoUrl);
                System.out.println("userInfo:"+userInfo);
                //微信那边采用的编码方式为ISO8859-1所以需要转化
                String json = new String(userInfo.getBytes("ISO-8859-1"), "UTF-8");
                System.out.println("====================userInfo==============================");
                JSONObject jsonObject1 = JSONObject.parseObject(json);
                String subscribe = jsonObject1.get("subscribe").toString();
                System.out.println("subscribe:"+subscribe);

                if(subscribe.equals("1"))
                {
                    session.setAttribute("subscribe","1");
                    System.out.println("subscribe:BBB");
                }

                //如果有绑定微信则登录
                User user = userService.selectUserByOpenid(openId);
                if (user != null) //如果有绑定微信则登录
                {
                    int userId = user.getUserId();
                    List<UserNo> userNoList = sysUserNoService.selectUserNoByUserId(userId);
                    if (userNoList != null) {
                        if (userNoList.size() > 0) {
                            request.getSession().setAttribute("userList", user);
                            request.getSession().setAttribute("userNo", userNoList.get(0));//手机号登录 默认为绑定的手机号的第一个会员编号
                            request.getSession().setAttribute("phone", 2);
                            request.getSession().setAttribute("dlopenid", openId);
                        }
                    }
                }

                return new Response(MessageConstants.MSG_SUCCESS, openId, "完成");
            } catch (Exception e) {
                return new Response(MessageConstants.MSG_SYS_ERROR, 0, e.getMessage());
            }
        } else {
            return new Response(MessageConstants.MSG_SYS_ERROR, 0, "");
        }
    }


}
